package com.sskj.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.sskj.http.bean.*;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestDialog extends JDialog {
    private JPanel contentPane;
    private String filePath;
    private String presenterName;
    private JTextField etShowDocUrl;
    private JButton connectShowDoc;
    private JTree jtree;
    private JTextField etDesc;
    private JTextField etRequestUrl;
    private JRadioButton radioPost;
    private JRadioButton radioGet;
    private JTextField etConstantName;
    private JTextField etMothedName;
    private JTextField etModelName;
    private JTextField etPresenter;
    private JRadioButton radioCreateModel;
    private JRadioButton radioGenerateToPresenter;
    private JRadioButton radioList;
    private JRadioButton radioPageBean;
    private JRadioButton radioBean;
    private JButton generateButton;

    private Project project;

    TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
// 设置选择可以包含任何数量的项，这些项不必是连续的。
            jtree.getSelectionModel().setSelectionMode(
                    TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
// 获取选中节点
            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) jtree
                    .getLastSelectedPathComponent();
            if (treeNode == null) {
                return;
            }
            System.out.println(treeNode);
// 获取选中节点的父节点
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) treeNode
                    .getParent();
            if (parent == null) {
                return;
            }

            System.out.println(parent);
            int selectedIndexMenu = parent.getParent().getIndex(parent);

// 获取选中节点的节点索引
            int selectedIndexItem = parent.getIndex(treeNode);
            ItemBean itemBean = postManBean.getItem().get(selectedIndexMenu).getItem().get(selectedIndexItem);

            try {
                execPythonItem(itemBean);
            } catch (Exception ex) {
                Messages.showMessageDialog(project, "异常", ex.toString(), Messages.getInformationIcon());
            }
            System.out.println(selectedIndexMenu);
        }
    };

    private List<ParamBean> paramBeans;

    private PostManBean postManBean;

    public TestDialog(Project project, String filePath) {
        this.project = project;
        this.filePath = filePath;
        this.presenterName = FileUtil.presenterFilePath;
        setTitle("测试");
        setLocation(100, 100);
        setBounds(0, 0, 500, 500);
        setContentPane(contentPane);
        setModal(false);

        ((DefaultMutableTreeNode) jtree.getModel()
                .getRoot()).removeAllChildren();
        jtree.updateUI();
        jtree.addTreeSelectionListener(treeSelectionListener);


        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        connectShowDoc.addActionListener(actionEvent -> {
            String showDocUrlText = etShowDocUrl.getText();
            try {
                execPython(showDocUrlText);
            } catch (Exception e) {

            }
        });
        etPresenter.setText(presenterName);
        String s = null;
        try {
            s = Utils.INSTANCE.FileInputStreamDemo(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (s == null) {
            return;
        }
        SaveBean saveBean = dealSaveBean(s);
        etShowDocUrl.setText(saveBean.getUrl());

        radioGet.addItemListener(itemEvent -> {
            int stateChange = itemEvent.getStateChange();
            if (stateChange == 1) {
                radioPost.setSelected(false);
            } else {
                radioPost.setSelected(true);
            }
        });
        radioPost.addItemListener(itemEvent -> {
            int stateChange = itemEvent.getStateChange();
            if (stateChange == 1) {
                radioGet.setSelected(false);
            } else {
                radioGet.setSelected(true);
            }
        });
        radioList.addItemListener(itemEvent -> {
            int stateChange = itemEvent.getStateChange();
            if (stateChange == 1) {
                radioBean.setSelected(true);
                radioPageBean.setSelected(false);
            }
        });
        radioPageBean.addItemListener(itemEvent -> {
            int stateChange = itemEvent.getStateChange();
            if (stateChange == 1) {
                radioList.setSelected(false);
                radioBean.setSelected(true);
            }
        });
        radioBean.addItemListener(itemEvent -> {
            int stateChange = itemEvent.getStateChange();
            if (stateChange == 2) {
                radioList.setSelected(false);
                radioPageBean.setSelected(false);
            }
        });
        generateButton.addActionListener(actionEvent -> {
            Messages.showMessageDialog(project, "生成中", "接口生成...", Messages.getInformationIcon());

            try {
                RequestBean requestBean = new RequestBean();
                requestBean.setParamBeans(paramBeans);
                requestBean.setBean(radioBean.isSelected());
                requestBean.setConstantName(etConstantName.getText());
                requestBean.setCreateModel(radioCreateModel.isSelected());
                requestBean.setDesc(etDesc.getText());
                requestBean.setGetPost(radioPost.isSelected());
                requestBean.setList(radioList.isSelected());
                requestBean.setMethodName(etMothedName.getText());
                requestBean.setModelName(etModelName.getText());
                requestBean.setPageBean(radioPageBean.isSelected());
                requestBean.setParseToPresenter(radioGenerateToPresenter.isSelected());
                requestBean.setPresenterName(etPresenter.getText());
                requestBean.setRequestUrl(etRequestUrl.getText());
                FileUtil.generateHttpConfig(requestBean);
                FileUtil.generateHttpService(requestBean);
                FileUtil.generatePresenter(requestBean);

                FileUtil.generateBean(requestBean);
                Messages.showMessageDialog(project, "接口生成成功", "提醒", Messages.getInformationIcon());

            } catch (Exception e) {
                e.printStackTrace();
                Messages.showMessageDialog(project, e.toString(), "接口生成失败", Messages.getInformationIcon());
            }
        });

    }

    public void execPythonItem(ItemBean itemBean) throws Exception {

        if (itemBean.getRequest().getUrlObject().getPath() == null) {
            throw new Exception("未获取到接口");
        }

        etDesc.setText(itemBean.getName());
        String requestUrl = dealRequest(itemBean);
        String getPost = itemBean.getRequest().getMethod();
        paramBeans = dealParam(itemBean);
        etRequestUrl.setText(requestUrl);
        etConstantName.setText(requestUrl.replaceFirst("/", "").replace("/", "_").toUpperCase());
        etMothedName.setText(Utils.INSTANCE.dealMothed(requestUrl));
        etModelName.setText(Utils.INSTANCE.dealModel(requestUrl));
        if (getPost.equals("POST")) {
            radioPost.setSelected(true);
            radioGet.setSelected(false);
        } else {
            radioPost.setSelected(false);
            radioGet.setSelected(true);
        }

    }

    public String dealRequest(ItemBean itemBean) {
        StringBuilder stringBuilder = new StringBuilder();
        itemBean.getRequest().getUrlObject().getPath().forEach(s -> {
            stringBuilder.append("/" + s);
        });
        return stringBuilder.toString();
    }

    public SaveBean dealSaveBean(String markdown) {
        String pattern = "\"([\\s\\S].*?)\"";

        String match;
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern, Pattern.UNIX_LINES);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(markdown);

        SaveBean saveBean = new SaveBean();
        m.find();
        m.find();
        saveBean.setUrl(m.group(1));
        m.find();
        m.find();
        m.find();
        m.find();
        return saveBean;

    }


    public List<ParamBean> dealParam(ItemBean itemBean) {

        ArrayList<ParamBean> paramBeans = new ArrayList<>();
        if (itemBean.getRequest().getMethod().equals("GET")) {
            itemBean.getRequest().getUrlObject().getQuery().forEach(queryBean -> {
                ParamBean paramBean = new ParamBean();
                paramBean.setValue(queryBean.getKey());
                if (queryBean.getDescription() != null) {
                    paramBean.setDesc(queryBean.getDescription().getContent());
                }
                paramBeans.add(paramBean);
            });
        } else if (itemBean.getRequest().getBody()!=null){
            if (itemBean.getRequest().getBody().getMode().equals("urlencoded")) {
                itemBean.getRequest().getBody().getUrlencoded().forEach(queryBean -> {
                    ParamBean paramBean = new ParamBean();
                    paramBean.setValue(queryBean.getKey());
                    paramBean.setDesc(queryBean.getDescription());
                    paramBeans.add(paramBean);
                });
            } else if (itemBean.getRequest().getBody().getMode().equals("formdata"))
                itemBean.getRequest().getBody().getFormdata().forEach(queryBean -> {
                    ParamBean paramBean = new ParamBean();
                    paramBean.setValue(queryBean.getKey());
                    paramBean.setDesc(queryBean.getDescription());
                    paramBeans.add(paramBean);
                });
        }

        return paramBeans;

    }

    public void execPython(String url) throws Exception {

        String str = HttpRequestUtils.sendGet(url);
        try {
            postManBean = new Gson().fromJson(str, PostManBean.class);

            SaveBean saveBean = new SaveBean();
            saveBean.setUrl(etShowDocUrl.getText());
            Gson gson1 = new GsonBuilder().disableHtmlEscaping().create();
            Utils.INSTANCE.StringBufferDemo(new File(filePath), gson1.toJson(saveBean));
            ((DefaultMutableTreeNode) jtree.getModel()
                    .getRoot()).removeAllChildren();
            jtree.updateUI();
            postManBean.getItem().forEach(pagesBean -> {
                updateTreeMenu(pagesBean);
            });
        } catch (Exception e) {
            Messages.showMessageDialog(project, "数据解析失败" + str, "警告", Messages.getInformationIcon());
        }
    }

    public void updateTreeMenu(ItemBean nodeToAdd) {
        DefaultTreeModel model = (DefaultTreeModel) jtree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) jtree.getModel()
                .getRoot();
        DefaultMutableTreeNode child = new DefaultMutableTreeNode(nodeToAdd.getName());
        model.insertNodeInto(child, root, root.getChildCount());
        nodeToAdd.getItem().forEach(itemBean -> {
            updateTreeItem(itemBean.getName());
        });
        jtree.scrollPathToVisible(new TreePath(child.getPath()));
    }

    public void updateTreeItem(String nodeToAdd) {

        DefaultTreeModel model = (DefaultTreeModel) jtree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) jtree.getModel()
                .getRoot();
        DefaultMutableTreeNode lastChild = (DefaultMutableTreeNode) root.getLastChild();
        DefaultMutableTreeNode child = new DefaultMutableTreeNode(nodeToAdd);
        model.insertNodeInto(child, lastChild, lastChild.getChildCount());
        jtree.scrollPathToVisible(new TreePath(child.getPath()));
    }


    private void onCancel() {
        // add your code here if necessary
        dispose();
    }
//
//    public static void main(String[] args) {
//        String a="{\"info\":{\"_postman_id\":\"9411f7c0-7c5b-4ab9-ab92-7313aea6e5dc\",\"name\":\"瀛︿範寮哄浗\",\"schema\":\"https://schema.getpostman.com/json/collection/v2.0.0/collection.json\",\"toc\":[],\"description\":\"<html><head></head><body></body></html>\",\"owner\":\"10698587\",\"collectionId\":\"9411f7c0-7c5b-4ab9-ab92-7313aea6e5dc\",\"publishedId\":\"Szf7zSkj\",\"public\":true,\"customColor\":{\"top-bar\":\"FFFFFF\",\"right-sidebar\":\"303030\",\"highlight\":\"EF5B25\"}},\"item\":[{\"name\":\"鐧诲綍\",\"item\":[{\"name\":\"鍙戦?佺煭淇￠獙璇佺爜\",\"_postman_id\":\"85f70381-8d84-44a3-a7e9-aa04b772c810\",\"protocolProfileBehavior\":{\"disableBodyPruning\":true},\"request\":{\"method\":\"POST\",\"header\":[],\"body\":{\"mode\":\"formdata\",\"formdata\":[{\"key\":\"deviceId\",\"value\":\"\",\"description\":\"<p>璁惧\uE62CID</p>\\n\",\"type\":\"text\"},{\"key\":\"phone\",\"value\":\"\",\"description\":\"<p>鎵嬫満鍙?</p>\\n\",\"type\":\"text\"}],\"options\":{\"formdata\":{}}},\"url\":\"web/sms/sendSmsCode\",\"description\":\"<p>鍙戦?佺煭淇￠獙璇佺爜</p>\\n\",\"urlObject\":{\"path\":[\"sms\",\"sendSmsCode\"],\"host\":[\"web\"],\"query\":[],\"variable\":[]}},\"response\":[]}],\"_postman_id\":\"10d60a50-d347-4683-bdca-b6dc620ddcc0\",\"description\":\"\"}]}";
//
//    }

}
